package com.jack.rxjava;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by zhang_j on 2019/10/21
 */
public class RxJavaTest {
    private static final Logger Log = LoggerFactory.getLogger(RxJavaTest.class);

    public static void main(String[] args) {
        //create()是Rxjava最基本的创造事件序列的方法
        //下面传入了一个OnSubscribe对象参数
        //当Observable被订阅时，OnSubscribe的call()方法会自动被调用，即事件序列就会依照设定依次被触发
        //即观察者会依次调用对应事件的复写方法从而响应事件
        //从而实现被观察者调用观察者的回调方法&由被观察者向观察者的事件传递，即观察者模式
        //创建被观察者Observable对象
        Observable<String> observable = Observable.create(new ObservableOnSubscribe<String>() {
            //通过ObservableEmitter类对象产生事件并通知观察者
            //ObservableEmitter是事件发射器，为了定义需要发送的事件&向观察者发送事件
            public void subscribe(ObservableEmitter<String> observableEmitter) throws Exception {
                observableEmitter.onNext("1");
                observableEmitter.onNext("2");
                observableEmitter.onNext("3");
                observableEmitter.onNext("4");
                observableEmitter.onComplete();
            }
        });

        Observer<String> observer = new Observer<String>() {
            public void onSubscribe(Disposable disposable) {
                Log.info( "开始采用subscribe连接");
            }

            public void onNext(String s) {
                Log.info("对Next事件作出响应" + s);
            }

            public void onError(Throwable throwable) {
                Log.info("对Error事件作出响应");
            }

            public void onComplete() {
                Log.info("对Complete事件作出响应");
            }
        };

        observable.subscribe(observer);

    }
}
